// pages/address/edit/edit.ts
import { addAddress, updateAddress, listSchool, listCampus } from "@/api/index";
import { showLoading, showToast } from "@/util/index";
interface IForm {
  id: number | null;
  schoolId: number | null; // 学校ID
  schoolName: string; // 学校名称
  campusId: number | null; // 校区ID
  campusName: string; // 校区名称
  locationName: string; // 用于UI展示的组合名称
  detailAddress: string;
  alias: string;
  isDefault: boolean;
}

Page({
  data: {
    // 2. [优化] 更新form的初始结构
    form: {
      id: null,
      schoolId: null,
      schoolName: "",
      campusId: null,
      campusName: "",
      locationName: "", // 初始为空
      detailAddress: "",
      alias: "宿舍",
      isDefault: false,
    } as IForm,
    aliasOptions: ["宿舍", "商户", "办公室"],
  },

  onLoad(options: { info?: string }) {
    if (options.info) {
      const info = JSON.parse(options.info) as IForm;
      console.log(info);
      this.setData({
        form: {
          id: info._id,
          schoolId: "1",
          schoolName: "",
          campusId: "1",
          campusName: "",
          locationName: info.address, // 初始为空
          detailAddress: info.formatted_address,
          alias: info.alias,
          isDefault: info.is_default,
        },
      });
      wx.setNavigationBarTitle({ title: "编辑地址" });
    } else {
      wx.setNavigationBarTitle({ title: "新建地址" });
    }
  },

  // 3. [核心改造] 使用 async/await 重构选择流程
  async handleChooseLocation() {
    try {
      showLoading({ title: "加载学校...", mask: true });

      // --- 步骤一：获取并选择学校 ---
      const schoolRes = await listSchool(); // 真实场景: await listSchool();
      if (!schoolRes) {
        wx.hideLoading();
        showToast("获取学校列表失败");
        return;
      }
      const schoolNames = schoolRes.map((s) => s.name);
      wx.hideLoading();

      const schoolActionSheetRes = await wx.showActionSheet({
        itemList: schoolNames,
      });
      const selectedSchool = schoolRes[schoolActionSheetRes.tapIndex];

      // --- 步骤二：根据学校ID，获取并选择校区 ---
      showLoading({ title: "加载校区...", mask: true });
      const campusRes = await listCampus(selectedSchool._id);
      console.log(campusRes);
      if (!campusRes || campusRes.length === 0) {
        wx.hideLoading();
        showToast("该学校暂无校区");
        return;
      }
      const campusNames = campusRes.map((c) => c.name);
      wx.hideLoading();

      const campusActionSheetRes = await wx.showActionSheet({
        itemList: campusNames,
      });
      const selectedCampus = campusRes[campusActionSheetRes.tapIndex];

      // --- 步骤三：更新表单数据 ---
      this.setData({
        "form.schoolId": selectedSchool._id,
        "form.schoolName": selectedSchool.name,
        "form.campusId": selectedCampus._id,
        "form.campusName": selectedCampus.name,
        "form.locationName": `${selectedSchool.name} - ${selectedCampus.name}`, // 组合用于显示
      });
    } catch (error: any) {
      wx.hideLoading();
      // 用户点击取消按钮会触发 fail 回调，其 errMsg 为 "showActionSheet:fail cancel"
      if (error && error.errMsg && error.errMsg.includes("cancel")) {
        console.log("用户取消选择");
      } else {
        showToast("操作失败，请重试");
      }
    }
  },

  handleSave() {
    const { form } = this.data;
    // 4. [优化] 校验逻辑现在可以基于更具体的字段
    if (!form.schoolId || !form.campusId) {
      return showToast("请选择学校和校区");
    }
    if (!form.detailAddress.trim()) {
      return showToast("请填写详细地址");
    }

    // 准备提交给后端的数据，可以剔除掉 locationName 这个纯UI字段
    const dataToSave: Omit<IForm, "locationName"> = {
      id: form.id,
      address: form.locationName,
      campusId: form.campusId,
      school: form.schoolName,
      detailAddress: form.detailAddress,
      alias: form.alias,
      isDefault: form.isDefault,
    };
    const formData = Object.fromEntries(
      Object.entries(dataToSave).filter(([key, value]) => value !== null)
    );
    console.log("准备保存的数据:", formData);
    showLoading({ title: "保存中..." });

    // 示例：根据是否有id判断是新增还是更新
    const savePromise = form.id
      ? updateAddress(formData)
      : addAddress(formData);

    savePromise
      .then((res) => {
        wx.hideLoading();
        showToast("保存成功");
        setTimeout(() => wx.navigateBack(), 800);
      })
      .catch((err) => {
        wx.hideLoading();
        showToast(err.message || "保存失败");
      });
  },

  // --- 其他方法保持不变 ---
  onDefaultChange() {
    this.setData({ "form.isDefault": !this.data.form.isDefault });
  },
  onDetailAddressInput(event: WechatMiniprogram.Input) {
    this.setData({ "form.detailAddress": event.detail.value });
  },
  onAliasChange(event: WechatMiniprogram.TouchEvent) {
    const { alias } = event.currentTarget.dataset;
    this.setData({ "form.alias": alias });
  },
});
